【问题标题】:Ajax enabled WCF in MVC returns 404在 MVC 中启用 Ajax 的 WCF 返回 404
【发布时间】:2014-02-12 21:01:55
【问题描述】:

我正在尝试将 WCF 服务添加到我的 MVC 项目中,以便有一个放置我的 ajax 方法的通用位置,但是当我尝试通过浏览 url 来调用它的方法时(例如 ../Service.svc/ HelloWorld)或使用 jquery ajax 调用它,我得到一个 404 页面。

如果我在 webforms 项目中做同样的事情,它可以正常工作。我在这里做错了什么?这不是保留 ajax 方法的最佳实践场所吗?就像我说的:我想要一个通用的地方来保存我的 ajax 方法,这些方法可能会被多个视图重用,所以如果可能的话,我不想把它们放在视图的控制器中

我的代码:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1:IService1
{
    public string HelloWorld()
    {
        return "HelloWorld";
    }
}
[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet]
    string HelloWorld();
}

我的配置:

<system.serviceModel>
    <services>
        <service name="WebApplication1.Service1">
            <endpoint address=""
                      behaviorConfiguration="AJAXEndpoint"
                      binding="webHttpBinding"
                      contract="WebApplication1.IService1" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="AJAXEndpoint">
                <webHttp />
                <enableWebScript />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior>
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="1" />
</system.serviceModel>

【问题讨论】:

  • 也许您正在寻找 MVC Web API?

标签: c# jquery ajax asp.net-mvc wcf


【解决方案1】:

您必须在 Global.asax 中添加ServiceRoute。你有一个 404 仅仅是因为这个请求没有路由。

例如,这可能是

routes.Add(new ServiceRoute("ThePath", new WebServiceHostFactory(), typeof(YourService)));

+1 for asp.net Web Api:这绝对是在 asp.net 中构建 Web api 的推荐方式,尤其是在现有的 mvc 项目中。

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 2016-09-28
    • 2020-12-02
    • 2016-07-17
    • 2011-01-04
    • 2016-05-26
    • 2012-12-24
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多