I am working on an email program for a WordPress WooCommerce store. I have added a webhook into the WooCommerce settings in order to hit a C# WebAPI application that I have created. I am trying to get run an email process every time an order is created.
I created an API controller with that accepts the JSON data that is sent over from WooCommerce, and when testing it locally from a Postman request, the controller is hit no problem.
I am trying to publish the application on Azure, and when I do, I am getting a 400 error from both the WooCommerce settings as well as any Postman requests.
I have tried setting
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
in the web.config file, which then returned a 502 error from Postman, but still the same error on the WooCommerce webhook side.
I also tried re-deploying which did not work either.
I am able to view the homepage as well as the API controller link on the standard MVC homepage/menu view.
The controller is a standard API controller inheriting from the APIController class:
public class OrdersController : ApiController
and it contains one method, ProcessOrders, with an [HttpGet, HttpPost] attribute on it, and a route of /api/orders/callback.
The controller is responsible for inserting the payload from the webhook into the database and then it uses some other classes email out some specific information about the product.
Is there some kind of setting that needs to be set in the Azure portal or on the web.config file? I am not very experienced with Azure so I am not too familiar if there is anything else that needs to be done for this.
Azure Information
I am deploying to azure from quick publish inside Visual Studio
A Pay-As-You-Go resource group
.Net Framework version 4.7
Remote debugging enabled
Web App app service
The only App service setting is WEBSITE_NODE_DEFAULT_VERSION set to 6.9.1
I have tried both Release and Debug configurations, the connection is valid when trying the Validate Connection option inside configuration, the File Publish Options are all unchecked (Remove additional files at destination, precompile during publishing, exclude files from app_data folder) and the publish works fine, and the app is accessible, except for the api controller.
The project is built as a .Net framework version 4.6.1 with Web API.
Thanks in advance for any help!
Edit
I have removed the parameter that was part of the original method that is being hit by the API, and I am now getting the error of No HTTP resource was found that matches the request URI. I have tried changing the Route data annotation as well as just making it HttpGet to see if it was accessible, and it is not working. I created a second action on the controller just to test returning a string, and that worked without problem, so I am not sure why it is not accessible. The intro to the method is as follows:
[HttpGet]
[Route("api/orders/callback")]
public string Callback() { return "Test"; }
I also updated this method to try just returning a simple string and it does not work. I also adjusted the second test method to accept a string POSTed to it and it is returning The requested resource does not support http method 'POST'.
This method looks like the following:
[HttpPost]
[Route("api/orders/new")]
public string SecondCallback(string payload) {
return payload;
}
Related
I'm working on an API for an Azure Static Web App. The web app is implemented in Angular (although that isn't important for this question), and the API is implemented in C# (NET 6). Deployment to Azure is via a GitHub action.
I can create an HTTP trigger API endpoint that works fine, like so:
public static class Tester
{
[FunctionName("Tester")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/tester")] HttpRequest req,
ILogger log)
{
return new OkObjectResult("Hello World");
}
}
I'm also able to access this directly via the SWA URL: https://<sitename>.azurestaticapps.net/api/v1/tester.
However, as soon as I add a reference to an Azure storage NuGet package to the project file (specifically Microsoft.Azure.WebJobs.Extensions.Storage.Blobs), making no other changes to the code, the API endpoint no longer works once deployed (although it will work locally).
On deploying the code with that package referenced in the .csproj, hitting the API endpoint gives a 503 status code with the response:
Function host is not running.
I enabled Application Insights for this static web app, and a CryptographicException is being thrown on startup:
An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. For more information go to http://aka.ms/dataprotectionwarning Could not find any recognizable digits.
(The link in the message doesn't go anywhere useful).
I'm presuming this has something to do with the AzureWebJobsStorage setting, which cannot be set in an Azure Static Web App (for whatever reason).
Based on all of the above, it would seem that using Azure storage from within a static web app C# function is verboten. However, I can't find that stated explicitly online anywhere. Has anybody got this kind of thing to work?
I removed the following nuget packages to make it working:
Microsoft.Azure.EventGrid
Microsoft.Azure.WebJobs.Extensions.EventGrid
I decomposed my http functions to a separate project because SWA does not support the EventTriggers right now.
I have a WEB Api project in ASP.NET Core 3.1; I am trying to use the same controller for showing a view and also for endpoints. The view will allow a user to input DB connection parameters and POST to an endpoint in the controller, which will write these settings to a file.
I was able to show the view only after deriving from Controller (changed from controller base). This link https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1, says if you plan to use the same controller for views and API, you should derive from Controller.
I am able to show my view but I am unable to post (using ajax) to an endpoint in the same controller. I am getting the following error:-
Failed to load resource: the server responded with a status of 400.
My controller is named Connection Controller and my endpoint is SaveConnection()
I am trying to Post to the SaveConnection endpoint using ajax, but I am getting the error (from console above).
My code in the view looks like below.
It looks like when posting to the endpoint, Connection/SaveConnection, I am unable to reach the endpoint, hence the 400 message.
Any ideas on how I can fix this?
You should serialize your obj first.
Can you try replacing the line "data:obj," with "data:JSON.stringify(obj),".
I'm new to asp.net mvc and web api. I'm reading a book which says:
ASP.NET MVC uses: System.Web.HttpRequest
and Web API Equivalent is System.Net.Http.HttpRequestMessage
and below is a picture that describes the request and result flow of web api
So my question is, how does hosting environment(which will typically be IIS) know that it should create a HttpRequestMessage object to represent the request from the client? I mean if the application is a MVC application, IIS should create a HttpRequest object instead of HttpRequestMessage, so how does IIS know which one to create?
As you can see from the picture you posted, the HttpRequestMessage exists only inside the "hosting" environment, web browser client does not know anything about that.
In the "hosting" world, IIS app pool is running the code you have built and deployed which knows very well wich framewok you are using as your code also contains the using assemblies you listed, System.Web... or System.Net...
Consider that even if you have shown separation between hosting, Controller and Action, all of that is running in same App Pool in IIS which, again, runs your code so knows what it is about as your IL assemblies were built from your specific source code.
I am not sure if I understand your question but this might be what you're looking for:
I mean if the application is a MVC application, IIS should create a
HttpRequest object instead of HttpRequestMessage, so how does IIS know
which one to create?
You must remember how you differentiate between a normal MVC Controller and a Web API Controller...
WebAPI Controllers enforces this annotation [ApiController] and must inherits from ControllerBase:
[ApiController]
public class PeopleController : ControllerBase {
//Your API methods here
}
A normal MVC Controller only inherits from Controller base class:
public class PeopleController : Controller {
//Your Action methods here...
}
Those already create configuration for your APP which becomes easier for you Hosting environment to know what is going and what to return when.
I hope you find this helpful.
I have a new Web API developed in ASP.NET Core. This Web API is supposed to be deployed in IIS and will have to work over SSL, so I have the [HttpsRequired] attribute on all my controllers. I struggle to make it work while deployed, so for now I relaxed the requirements and commented out those attributes. Doing so, I was able to create two bindings in IIS, one for HTTPS and one for HTTP. Given that my Web API is created in ASP.NET Core, I followed the deployment steps Rick Strahl has in his excellent blog post. I have selected "No Managed Code" for the .NET CLR version. The IIS machine is a 64-bit Windows Server 2012 R2 environment - not sure whether this matters or not. The .NET Core Windows Server Hosting bundle has been installed on the server and I can see the AspNetCoreModule listed in the Modules grid.
If i try to access the Web Api (I created a very simple GET method that returns some information regarding the assembly) with Fiddler, I get a 404 error. For now, i run Fiddler on the same machine, so I tried all combinations (localhost, IP address and full machine name in the domain).
No errors are logged in the EventViewer. Does anyone have any suggestion on how to troubleshoot this issue?
TIA,
Eddie
EDIT1: Here is my controller:
[Route("api/info")]
//[RequireHttps]
public class InfoController : Controller
{
private ITncRepository _repository;
public static ApplicationAssemblyDetails ApplicationAssemblyDetails { get; set; }
public InfoController(ITncRepository repository)
{
_repository = repository;
ApplicationAssemblyDetails = ApplicationAssemblyDetails.Current;
}
[HttpGet("")]
public JsonResult Get()
{
return Json(new WebApiInfoModel()
{
CurrentTime = DateTime.Now,
CurrentUtcTime = DateTime.UtcNow,
AssemblyName = ApplicationAssemblyDetails.ApplicationAssembly.FullName,
VersionNumber = ApplicationAssemblyDetails.VersionNumber,
BinFolder = ApplicationAssemblyDetails.BinFolder,
BuildMode = ApplicationAssemblyDetails.BuildMode,
TradeMark = #" © 2016-2017 * SomeCompany (www.somecompany.com)"
});
}
}
The ApplicationAssemblyDetails is a nuget package that gives some info about the current assembly. WebApiInfoModel is my model class for the Web API Information I want to pass back as a test to the client.
The web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\My_ASP_NET_Core_Web_API.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
</system.webServer>
</configuration>
Finally, to answer your last question, Ignas, I use a Publishing Profile that uses the File system as a method, targets the .NET Framework 4.5.2, using the release configuration. Given that my project is a Web API and not an MVC 6 Web Application, the publishing package creates a stand-alone application. Since the clients need to call my Web API using SSL, I think that it has to be hosted in IIS, so running the standalone application would not work. Of course, for testing purposes, I could try to run it. That's why I commented out the [HttpsRequired] attribute. I will try that and report back, but for now I hope I gave you all the information you required.
I'm having a setup very close to yours (Asp.Net core, Web API, IIS, HTTPS ...) working fine on my end.
I faced the same issue at some point because I was not using the proper path to access my controller/action, it depends on how you deployed it under IIS. For instance, in my case when I use Kestrel directly it goes through a URL like that:
http:// localhost:5000/controllerName/actionName
But I can also contact my Web API via IIS and in that case I need to use a URL like that:
http:// localhost:5001/applicationName/controllerName/actionName
Have you created an application under IIS that could explain you getting a 404 because you would not use the proper path?
For instance, in my case:
screenshot of the asp.net core api under iis
And I'm accessing it, through the URL:
https: //servername:serverport/RequestPortalAPI/ControllerName/ActionName
In the end, it was a matter of properly configuring Widows Authentication. For Fredrik and anyone else reading this post for a solution, these are the steps I performed:
In IIS, in the Authentication form for my Web API, I disabled Anonymous Authentication and I enabled Windows Authentication:
Make sure that "Negotiate" is at the top of the list for Enabled Providers:
In the Application Pools, I configured my Web API to run under an account that the UIT department of my client has given me:
The configuration file of my Web API (web.config) contains the following settings:
Now we are getting into the dark areas of the problem. In order to use Windows Authentication and let the credentials of the caller be passed through to the backend (in my case a SQL Server database), the Web API has to be configured to use Kerberos. I found this after I opened a ticket with Microsoft and I worked closely with one of their engineers. For this to happen, you need to follow these steps:
Create a Service Principal Name (SPN) for your Web API and the domain account it runs under. You need to run this command:
Where hostname is the fully qualified domain name of your Web API. The Domain\Username are the domain account under which the Web API is running. You need special domain privileges, so you may want to involve someone from IT. Also, from now on, you need to access your Web API by the full domain name, not by IP address. IP address won't work with Kerberos.
Also, with the help of your IT person, you need to enable delegation for any service using Kerberos for the domain account under which you run your Web API. In the Active Directory Users and Computers, locate the account you use to run your Web API, bring up its properties, click on the Delegation tab and enable the second option "Trust this user for delegation to any service (Kerberos Only):
We have also made some changes on the server that runs our database, but I am not 100% those are truly required, so I won't add them here because I don't even know if you use SQL Server or some other backend repository.
Let me know if you need those as well and I will add them later.
Good luck,
Eddie
I have hosted many ASP.NET and MVC applications before. I was playing with MVC6 lately and tried to host an MVC6 application.
Everything works fine if I host it as a new website. When I host it as an application under the default website of IIS, it only shows an empty page. Please find the log information below
warn:
Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when
application exits. warn:
Microsoft.AspNet.DataProtection.Repositories.EphemeralXmlRepository[0]
Using an in-memory repository. Keys will not be persisted to storage. Hosting environment: Production Now listening on:
http://localhost:23000 Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNet.Hosting.Internal.HostingEngine[1]
Request starting HTTP/1.1 GET http://localhost/MVC6 info: Microsoft.AspNet.Hosting.Internal.HostingEngine[2]
Request finished in 0.0687ms 404
Note: Default website uses application pool asp.net4.5 and my MVC6 application uses it's own application pool as mentioned in http://docs.asp.net/en/latest/publishing/iis.html#iis-server-configuration
Anyone else faced similar problem like this? I want to know how to make it work under default website
Edit: This is a bug in vs2015 rc1 https://github.com/aspnet/Hosting/issues/416#issuecomment-149046552.
There is a workaround for this bug in above link but I followed a different method because I need to host my application in more than one website without republishing.
I resolved the above problem using the Route attribute. After adding the route attribute to an action result, application works fine
public class HomeController : Controller
{
[Route("MVC6")]
[Route("")]
public IActionResult Index()
{
return View();
}
}