从jQuery-MVC 2调用支持AJAX的WCF服务

Psy*_*der 6 wcf jquery asp.net-mvc-2

我已经完成了大量的阅读,看起来很简单.我创建了我的服务,这非常简单(看起来像这样

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeddingPhotographerService
{    
    // Add more operations here and mark them with [OperationContract]
    [OperationContract]
    public bool AddNewSkill(string name, string description)
    {
        IRepository<Skill> skillRepo = ObjectFactory.GetInstance<IRepository<Skill>>();

        var skill = new Skill { Name = name, Description = description };
        skillRepo.Save(skill);
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

很简单,然后我在我的视图中写了这个jQuery代码

$(document).ready(function () {
    $("#AddSkill").click(function () {
        var data = { name: $("#NewSkill").val(), description: "" };
        data = JSON.stringify(data)
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WeddingPhotographerService.svc/AddNewSkill",
            data: data,
            dataType: "json",
            success: function () {
                $('#SkillListViewContainer').load('../AccountController/GetSkillControl');
            },
            error: function (msg) {
                $("#AddSkillError").text(msg.d);
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我的WeddingPhotographerService.svc位于项目的根目录中,web.config在我创建服务时添加了这个

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="WeddingPhotographer.WeddingPhotographerServiceAspNetAjaxBehavior">
        <enableWebScript />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WeddingPhotographer.WeddingPhotographerService">
      <endpoint address="" behaviorConfiguration="WeddingPhotographer.WeddingPhotographerServiceAspNetAjaxBehavior"
        binding="webHttpBinding" contract="WeddingPhotographer.WeddingPhotographerService" />
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
    multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

一切看起来都很简单,看起来它应该可以工作但是当我点击AddSkill Chrome JavaScript控制台时会返回404错误,所以它根本找不到服务(我打开了控制台,因为当我点击它时什么都没发生按钮).

我在这里错过了什么吗?

顺便说一下,我也尝试了这个(因为这是web.config文件中的名字)

url: "WeddingPhotographer.WeddingPhotographerService.svc/AddNewSkill"
Run Code Online (Sandbox Code Playgroud)

我仍然得到资源未找到(404)错误

Psy*_*der 4

解决了,将jQuery AJAX 调用中的url行更改为

url: "../WeddingPhotographerService.svc/AddNewSkill"
Run Code Online (Sandbox Code Playgroud)

一切都很好