ServiceStack Cors

2019-07-23 21:17发布

问题:

I am building a project and wish to implement CORS. It is installed on a shared IIS server (shared hosting).

In my apphost.cs I enable and configure CORS according to several of the articles I find on the web.

Plugins.Add(new CorsFeature(
     allowedMethods: "GET, POST, PUT, DELETE, OPTIONS", 
     allowedOrigins: "*", 
     allowCredentials: true, 
     allowedHeaders: "content-type, Authorization, Accept"));

I also read that when implementing the newer SS API (IService) I had to provide a hook for the 'Options' call so I added...

this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
     //Handles Request and closes Responses after emitting global HTTP Headers
     if (httpReq.HttpMethod == "OPTIONS")
         httpRes.EndRequest();  //add a 'using ServiceStack;'
     });

I am able to call my api via REST Console (chrome addin) but when I call with a ajax request I get a 405 error.

Request URL:http://empire.thecodingpit.com/api/engine
Request Method:OPTIONS
Status Code:200 OK

Request Headers view source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:empire.thecodingpit.com
Origin:http://json.commublogs.com
Referer:http://json.commublogs.com/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)                  Chrome/29.0.1547.66 Safari/537.36
Response Headers view source
Cache-Control:private
Content-Length:0
Date:Thu, 26 Sep 2013 17:00:59 GMT
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-MiniProfiler-Ids:  ["f8c3ddb8434149feb689dd44d93bf862","6d0e7e0f8ac1456d98872a82af4d6602","67bdf08a19c641a7b26db0b43fd10888","1819b1ce3e314c0594ef9ecb1ac68fcf","7af8595373e345f3a9f8ade60c8a7817"]
X-Powered-By:ASP.NET

I do not have any [Authentication] on my methods - yet.

I have looked at this question and have implemented it as shown above. This related question is NOT a duplicate. servicestack REST API and CORS

The service call (POST) that I am making is...

public object Post(SelectedTroops request)
{
     return new SelectedTroopsResponse { ArrayOfSelectedTroops = request.ArrayOfSelectedTroops };

}

If I am missing anything that may be helpful please let me know. I guess an side note question may be - how do you effectively trace thru and debug something like this? Any helpful hints would be more than appreciated.

回答1:

You do have to use:

httpRes.EndRequest();

It's important, it's an extension method in the ServiceStack namespace. I recommend using Tools like ReSharper which makes auto-finding and referencing extension methods trivial.