这已被问了一百万次但是......
我有一个WebAPI。它适用于运行IIS的本地计算机。但在部署到服务器后,它失败了。
我尝试过的事情:
已添加
<modules runAllManagedModulesForAllRequests="true">
将处理程序设置为
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
将json添加为MIME类型
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
路由映射为
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
启动文件:
public static void ConfigureContainer(IAppBuilder app)
{
var builder = new ContainerBuilder();
var options = CreateCorsOptions();
app.UseCors(options);
// Get your HttpConfiguration.
config = new HttpConfiguration();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(config);
RegistererWebApi(builder, config);
// Register dependencies, then...
var container = builder.Build();
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
// Register the Autofac middleware FIRST. This also adds
// Autofac-injected middleware registered with the container.
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.UseWebApi(config);
}
private static void RegistererWebApi(ContainerBuilder builder, HttpConfiguration config)
{
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// OPTIONAL: Register the Autofac filter provider.
//builder.RegisterWebApiFilterProvider(config);
}
更新
这是我的完整WebApiConfig:
public static class WebApiConfig
{
/// <summary>
/// Register the WebAPI. Remove Xml formatter (OPnly using JSON). Add filters. Set Routing
/// </summary>
/// <param name="config"></param>
public static void Register(HttpConfiguration config)
{
//Enable cross origin requests
var cors = new EnableCorsAttribute("http://local.isos.com,htt://dev.isos.mydelphic.com,http://qa.isos.mydelphic.com,http://localhost/", headers: "*", methods: "*");
config.EnableCors(cors);
// Web API configuration and services
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Filters.Add(new UnhandledExceptionFilter());
config.MessageHandlers.Add(new CacheCow.Server.CachingHandler(config));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
UPDATE2
以下是我使用Autofac注册控制器的方法
private static void RegistererWebApi(ContainerBuilder builder, HttpConfiguration config)
{
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
}
这是我的控制器:
[RoutePrefix("providers")]
public class ProviderController : BaseApiController
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="requestDispatcher">Dispatcher gets injected by Ioc</param>
public ProviderController(IRequestDispatcher requestDispatcher)
: base(requestDispatcher)
{ }
/// <summary>
/// Get a list of all providers outside the Philipines
/// </summary>
/// <returns>Returns an action result regarding the state of the request. Returns a 200 containing the list of providers. Returns a 404 is no results are found.</returns>
[Route("",Name="Providers")]
public async Task<IHttpActionResult> Get(string sort = "ProviderName", int page = 1, int pageSize = 10)
{
var query = new GetProviders();
// Populate the view model by calling the appropriate handler
var providers = await RequestDispatcher.DispatchAsync<GetProviders, ProvidersResponse>(query);
if (providers == null)
{
return NotFound();
}
var totalCount = providers.Count;
var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
var urlHelper = new UrlHelper(Request);
//Route name
var prevLink = page > 1 ? urlHelper.Link("Providers",
new
{
page = page - 1,
pageSize = pageSize,
sort = sort
}) : "";
var nextLink = page < totalPages ? urlHelper.Link("Providers",
new
{
page = page + 1,
pageSize = pageSize,
sort = sort
}) : "";
var paginationHeader = new
{
currentPage = page,
pageSize = pageSize,
totalCount = totalCount,
totalPages = totalPages,
previousPageLink = prevLink,
nextPageLink = nextLink
};
HttpContext.Current.Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));
return Ok(providers);
}
}
答案 0 :(得分:1)
您似乎正在使用OWIN,而不是旧式单身GlobalConfiguration
...但您已在GlobalConfiguration
上设置依赖项解析程序。
尝试设置config.DependencyResolver
。 Check the docs for example/explanation.
答案 1 :(得分:0)
这是配置设置。在服务器上,虽然仍然运行IIS7,但它是较旧的服务器,您需要明确告诉IIS查找OWIN启动类:
killall -9 python