pubsubhubbub and Dot NET core API - api

I'm trying to subscribe to pubsubhubbub push notifications here : https://pubsubhubbub.appspot.com/subscribe
To achieve this, I created an API that returns the value of hub challenge.
Here is the code of my API :
[Route("api/[controller]")]
[ApiController]
public class WHYoutubeSubscriberController : ControllerBase
{
[HttpGet()]
public string Get(string hub_topic, string hub_challenge, string hub_mode, string hub_lease_seconds)
{
return $"{hub_challenge}";
}
Using Webhook.site, I check how the parameters are sent to the callback url : https://webhook.site/4a4f3ed9-8b72-4947-91a7-c0d39338aeb2?hub_topic=https%3A%2F%2Fwww.youtube.com%2Fchannel%2FUCiq8sdtkxlzjkpx3fBiXqqw&hub_challenge=7295589196100610421&hub_mode=subscribe&hub_lease_seconds=432000
Locally, the hub challenge value is properly sent back, so I don't understand why I still get a (Challenge mismatch.) error.
This error is shown when I use the Subscriber Diagnostics.

Related

How does Swagger achieve the same route but different query parameters?

I created an asp.net core web api project, using the .net5 version, and I have a route like this.
[Route("api/detail")]
public IEnumerable<User> Get()
{
//TODO
return users;
}
[Route("api/detail")]
public IEnumerable<User> Get(string name)
{
//TODO
return users;
}
Although my request method is the same and the request parameters are different, the 500 error will be reported in swagger. Is there any way to solve it? Any help is greatly appreciated.
There could be multiple reasons why you're getting a 500 error. When I pasted your code into a new controller the first is error I received was:
Ambiguous HTTP method for action... Actions require an explicit HttpMethod binding for Swagger
It's telling you that you need to decorate each action in the controller with an HttpMethod binding, like [HttpGet]. More on that in a second...
The next issue is that you're using [Route] to bind two different action methods to the exact same route with the same HttpMethod. That's not possible in an API controller.
Conflicting method/path combination... Actions require a unique
method/path combination for Swagger
My preferred method for routing is to use Attribute routing with Http verb attributes.
The first step would be to move the route attribute to the controller. I'm going to assume you've created a DetailsController:
[Route("api/[controller]")]
[ApiController]
public class DetailsController : ControllerBase { }
Now, update your actions. Remove the [Route] attribute, replace with the HttpGet attribute, and add the name parameter to your second endpoint. I also prefer to return an IActionResult:
[HttpGet]
public IActionResult Get()
{
//TODO
return Ok(users);
}
[HttpGet("{name}")]
public IActionResult Get(string name)
{
//TODO
return Ok(users);
}
Note that parameters are identified by using curly braces around the variable {name} in the Http method attribute. Both endpoints work and are accessible through swagger. I urge you to read the linked page above for a better understanding of the possible routing options (linked again).

Trouble Getting Twilio SMS Response from ASP.NET Core MVC Endpoint

When I setup request bin, I get a response that seems totally normal (see screen shot below). When I use the command
ngrok http 5000
And I send the response to my local http endpoint, ngrok reports 200OK if my POST method in the controller has no parameters. Even if I add one parameter ([FromBody] string content), I get a 400 bad request out of ngrok's console.
I'm pasting below a couple different POST method's I've tried. I've tried inheriting my controller from controllerbase and controller and get the same behavior.
[HttpPost]
public string JsonStringBody([FromBody] TwilioSmsModel twilioSmsModel)
{
return "";
}
POST: api/SmsBody
[HttpPost]
public async Task<IActionResult> PostTwilioSmsModel([FromBody] TwilioSmsModel twilioSmsModel)
public async Task<IActionResult> Post()
{
var twilioSmsModel = new TwilioSmsModel();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TwilioSmsModels.Add(twilioSmsModel);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTwilioSmsModel", new { id = twilioSmsModel.SmsSid }, twilioSmsModel);
}
If there is a github example of sms notifications working with asp.net core 2.1, that would be a big help.
Twilio developer evangelist here. Most likely the error you're seeing has nothing to do with the way you're building your application, but with the fact that .NET expect some host headers to be passed in order to process your request. And why it works with requestbin.
You haven't specified any error message in your question, so this is guesswork, but try changing your ngrok commend to the following:
ngrok http 5000 -host-header="localhost:5000"
And you should stop seeing the 400 error you're getting and the requests should go through normally.
Hope this helps.

Is there a helper method to extract origin host from request (to build a link)

I receive request via a router :
#Bean
public RouterFunction<ServerResponse> routerFunction() {
return nest(path(API_PATH), route(GET("/"), indexHandler::getIndex));
}
handle by a method :
public Mono<ServerResponse> getIndex(ServerRequest request) {
...
}
I need to extract the url use to request the service, I have different cases, sometimes request are direct to service, sometimes request go through proxy (and add X-Forwarded-Path,X-Forwarded-Path headers).
Is there a helper method, to extract this details from ServerRequest object ?

Web Api 2 Attribute Routing, 404 and 405 codes

I created a testing Web Api 2 in .Net 4.5.2.
The controller code is
using System.Web.Http;
using MyService.Models;
namespace MyService.Controllers
{
public class DefaultController : ApiController
{
[HttpPost]
[Route("Members/")]
public IHttpActionResult CreateRequest(MyRequestDto request)
{
return this.Ok();
}
[HttpGet]
[Route("Members/{id : int}")]
public IHttpActionResult GetMember(int id)
{
var response = new MyRequestDto()
{
FirstName = "Test F " + id,
LastName = "Test L " + id
};
return this.Ok(response);
}
}
}
The web api config code is
using System.Web.Http;
using MyService.Infrastructure;
namespace MyService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
}
But when I request the services from soapUI I got
404 http code for posting some JSON to http://localhost:15945/Members/
405 http code for getting from http://localhost:15945/Members/123
It looks like the routing is not working properly. But why?
I'm not sure but what about declare routing attribute on the class-
something like this:
[RoutePrefix("api")]
public class DefaultController : ApiController
You got error of 404 or 405 (for post), so that mean that your request didn't reach the web api.
404
if the request URI did not match a route for the Web API application, the server would return an HTTP 404 Not Found error.
405
A request method is not supported for the requested resource; for example, a GET request on a form which requires data to be presented via POST, or a PUT request on a read-only resource.
should be call
For JSON to http://localhost:15945/api/Members/
For http code for getting from http://localhost:15945/api/Members/123
please check this link http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
You have some syntax errors in your route templates. You should read up some more on Attribute Routing.
Given that here is your fixed controller.
public class DefaultController : ApiController
{
//POST Members
[HttpPost]
[Route("~/Members")]
public IHttpActionResult CreateRequest(MyRequestDto request)
{
return this.Ok();
}
//GET Members/123
[HttpGet]
[Route("~/Members/{id:int}")]
public IHttpActionResult GetMember(int id)
{
var response = new MyRequestDto()
{
FirstName = "Test F " + id,
LastName = "Test L " + id
};
return this.Ok(response);
}
}
Explanation:
Your original prefix for the POST method included a slash with out a parameter so it treated the slash as a literal part of the template.
Your GET method's template had bad syntax [Route("Members/{id : int}")] for the id parameter. {id : int} should not have spaces in the constraint is {id:int}.
A couple updates to your Route attributes and you should be fine:
Remove the trailing slash, change [Route("Members/")] to [Route("Members")]
Remove the spaces, change [Route("Members/{id : int}")] to [Route("Members/{id:int}")]
You don't need route prefixes, you don't need the tilde in front as the other answers suggest. We have hundreds of routes defined just like this across many different API projects and they work just fine.
The 404 error you are getting is because the trailing slash is part of your route definition, but the actual URI is without the slash even if you include the slash in your request because somewhere in the default asp.net pipeline or even IIS is set to remove the trailing slash. So the actual route never matches your attribute resulting in a 404.
The 405 error you are getting is because the spaces in the route attribute actually messed up the id variable so the route that was getting matched was your POST route and a GET is not allowed resulting in a 405.

WCF service returns Error:System.Xml.Schema.XmlSchemaValidationException:

My application is accessing a WCF service hosted at the server.
When i try to call a Method with [WebInvoke] attribute the response returned is always "error".
All other methods with [WebGet] attribute are working fine.
The interface as in the reference.cs is
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="SyncService.IService")]
public interface IService
{
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[System.ServiceModel.OperationContractAttribute(Action="", ReplyAction="")]
[System.ServiceModel.FaultContractAttribute(typeof(DataSynchronization.SyncService.WebExceptionDetail), Action="Update", Name="WebExceptionDetail", Namespace="http://schemas.datacontract.org/xxx.WebServices")]
string Update(string mode, string data);
}
whenever i try to call the Update method of the service using the code
string response = objClient.Update("manual", string data);
the response obtained is "Error".and the log displays
Error -
"System.Xml.Schema.XmlSchemaValidationException:
The element 'providers' cannot contain
text. List of possible elements
expected: 'provider'". on calling
Update
The service is hosted in a remote server which i cannot debug either.