GVKun编程网logo

ASP.NET MVC和Angularjs一起+ ASP.NET Web API(asp.net mvc与asp.net的区别)

11

在本文中,我们将详细介绍ASP.NETMVC和Angularjs一起+ASP.NETWebAPI的各个方面,并为您提供关于asp.netmvc与asp.net的区别的相关解答,同时,我们也将为您带来关

在本文中,我们将详细介绍ASP.NET MVC和Angularjs一起+ ASP.NET Web API的各个方面,并为您提供关于asp.net mvc与asp.net的区别的相关解答,同时,我们也将为您带来关于AngularJS + ASP.NET Web API + ASP.NET MVC身份验证、AngularJs -.net MVC WebApi身份验证示例、angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core、ASP.NET MVC Web API2 AngularJS授权和身份验证的有用知识。

本文目录一览:

ASP.NET MVC和Angularjs一起+ ASP.NET Web API(asp.net mvc与asp.net的区别)

ASP.NET MVC和Angularjs一起+ ASP.NET Web API(asp.net mvc与asp.net的区别)

我想知道使用这两个世界的优点和缺点:

  • ASP.NET MVC和Angularjs一起使用(无需剃须刀,Angularjs即可完成工作)。
  • AngularJS(前端)+ ASP.NET Web API(后端)。

我们专注于具有大量服务器端业务规则和计算的大中型企业项目的SPA / Mini-SPA。我也关注安全性。

优缺点意见将帮助我在脑海中找到这个问题的答案:

一起使用ASP.NET Web API(后端),ASP.NET MVC和Angularjs是明智的决定吗?

答案1

小编典典

是的,将两者结合起来是明智的。显然,根据具体项目,您需要调整最终解决方案中的某些变量。

您所建议的实际上是我们最近2或3个项目的堆栈,根据特定要求在此处和此处有一些变体。我们已经使用了WebAPI + DurandalJS,WebAPI +
Knockout …一切都很好:) AngularJS似乎使用了最长的时间,在我们公司内部以及在社区的其他地方都越来越受欢迎(这是决定性的)对我来说)

当前技术堆栈。

                            +------------------------------------+                            |               Usage                |  +-------------------------+------------------------------------+  | AngularJS               | The client app web, or mobile      |  +-------------------------+------------------------------------+      | WebAPI                  | For all your data access needs     |  +-------------------------+------------------------------------+  | OAuth & Bearer Tokens   | For Authentication & Authorization |  +-------------------------+------------------------------------+  | SQL Server & EF / any   |  Persistence                       |  | any other noSQL variant |  & Storage                         |  +-------------------------+------------------------------------+  | Angular-UI /            |                                    |  | Angular-Material        | Base UI components                 |  +-------------------------+------------------------------------+  | Katana                  | Collection of projects for         |  |                         | supporting OWIN on MS-Stack        |  +-------------------------+------------------------------------+  | CORS                    | Standard for implementing          |  |                         | cross domain requests              |  +-------------------------+------------------------------------+

优点:

  • Web App可以很容易地移植到移动设备上(如果您以可能会移动的方式编写)

    • 使用科尔多瓦
    • 您拥有一个可以轻松选择使用其他服务/应用程序访问的API。此外,API很酷(与传统访问机制相比)
  • AngularJS允许使用功能强大且结构化的客户端代码(不是没有Angular就无法做到这一点,但以我的经验,如果您正确地遵循它们,框架将实施更好的实践)

  • 开始听起来像是破记录,但是众所周知,AngularJS可以进行超级测试

  • 如果您害怕NodeJS和grunt / gulp之类的东西,可以使用.Net捆绑

    • 并不是您一定要害怕它(而是熟悉>不熟悉)
    • 只要确保以Minsafe方式编写客户端代码
    • 实际上,Visual Studio的开发非常酷,特别是因为它们最近都将重点放在对开源的支持上。AngularJS,Node(有时可能会用到)和ASP.Net MVC的许多集成点

缺点:

  • 如果您不熟悉Angular,学习曲线会很不错

  • 可能重复验证

    • 为了减少往返行程/回调,显然最好在第一次执行时就发送正确的数据。因此,在少数(或大多数)实例中,我们需要复制JavaScript中的某些数据级别验证
    • 尽管它可能不适用,并且有点远…我去过一个客户那里,他们严格地希望使用MS的一切,因为开源是“不太安全的”,因为人们可以访问框架代码。 .. 去搞清楚。因此,请确保他们愿意使用开放源代码的SPA框架(这可能适用于任何其他框架或工具)(及其附带的所有内容)
  • 安全性重复。您需要确保保护API和应用程序的安全。(由于两层之间存在断开连接)

  • 您需要学习CORS的工作原理,以及如何正确隐含CORS,因为您的API和Web应用可能不在同一个域/源上

AngularJS + ASP.NET Web API + ASP.NET MVC身份验证

AngularJS + ASP.NET Web API + ASP.NET MVC身份验证

我是AngularJS的新手,正在尝试为我的新Web应用程序对其进行评估。

需求:

我将有一个ASP.NET Web API,它将从Android,iPhone和Web应用程序(ASP.NET MVC)中使用。ASP.NET
Identity将在Web API中实现。这三个应用程序都将调用Web API的login方法来获取auth令牌。

问题:

我的问题是当Angular进行调用以获取HTML模板/视图,JavaScript文件时,如何获得ASP.NET MVC 服务器端身份验证
工作(与Web API同步,因此我不必分别登录ASP.NET
MVC)或其他资源。我在AngularJS上浏览了许多文章和博客,但仍然找不到适合我要求的安全模型。

可能的解决方案:

将登录调用直接调用ASP.NET MVC应用程序而不是Web API是一个好主意,并且ASP.NET MVC应用程序将调用Web
API进行登录,并在进行身份验证之后,将auth令牌保存在会话中并创建一个 FormsAuthentication cookie
和cookie数据中的数据将保存加密的auth令牌。此外,在HTML的 ng-init 中将 auth令牌
设置为AngularJS范围内的令牌。现在,当AngularJS尝试调用ASP.NET
MVC应用程序以获取HTML时,然后通过将cookie中解密的数据与会话中的auth数据进行匹配来对用户进行身份验证/授权。另外,AngularJS将
在标头中 发送 auth令牌,以 直接 调用Web API方法 ,以用于随后通过Web API进行数据操作的所有后续调用。

答案1

小编典典

我用非常严格的向前解决方案解决了这个问题。我只是确保在WebApiConfig的Register方法中有以下两行代码:

config.SuppressDefaultHostAuthentication();config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

而已。现在,我的MVC控制器在寻找会话cookie以进行授权,而我的Web API控制器在每个请求的标头中寻找auth令牌。此外,Web
API会响应登录/身份验证请求(例如)发送令牌(JSON)和会话cookie本身http:\\www.mydomain.com\token

因此,现在我将登录请求发送到Web
API以获取令牌以及会话cookie。会话Cookie将在每个请求时自动发送,因此我不必担心MVC控制器的授权。对于Web
API调用,我将在每个请求的标头中发送auth令牌,因为Web API控制器不关心与请求一起发送的会话cookie。

AngularJs -.net MVC WebApi身份验证示例

AngularJs -.net MVC WebApi身份验证示例

我有一个.Net MVC WebApi应用程序,并尝试在 Angularjs中专门编写前端.我能够通过json获取数据并对其进行操作,但我现在需要保护数据并将Base64身份验证添加到服务器的标头中.当我浏览一些我的.net视图测试页面时,我得到了相应的登录框,询问用户/通行证,以便我可以继续获取json.

我不知道该怎么做是在我的$资源中设置角度的标题中传递此信息(用户/通行证).有没有完整的例子可以更好地告诉我如何做到这一点?我知道它涉及cookie并使用服务器传回的令牌,但我不知道如何将各个部分放在一起.

当我把所有这些结合在一起时,我希望通过所有层(DAL,RESTFUL,控制台测试层)发布一个完整的骨架示例.

所以问题是 – 在使用AngularJS $资源时,如何将身份验证信息插入客户端的标头中?

谢谢

如果你在服务器端的头部放一个cookie,AngularJS将一直发送这个cookie.你无事可做.

如果你想在Header中传递令牌而不是在Angular端的cxookie中传递令牌,请执行以下操作:$httpProvider.defaults.headers.common [‘X-Auth’] = yourKey;在您的配置块中.

然后,如果您想知道用户是否已登录,或者他是否拥有权限,则只需实现拦截器.这是一个简单的工厂,你会在你的配置块中推送响应者.

该工厂将监听来自服务器的每个响应,并且在他的实现中,您将检查错误情况下响应的状态代码:

401 – >没有记录
403 – >没有授权

工厂的例子:

myModule.factory('myHttpInterceptor',function ($q) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success              
            return response;
        },function (response) {
            // do something on error
            //check status 401 or 403
            return $q.reject(response);
        });
    };
});

然后把你的工厂放在你的con fig块中的http responseIntercetors中:

myModule.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
});

请记住,AngularJS 1.1.4中不推荐使用此解决方案(仍然不稳定)……

工厂必须有所不同,请参阅这篇文章了解更多信息:AngularJS Intercept all $http JSON responses

希望能帮助到你

angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core

angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core

我正在使用带有TypeScript和ASP.NET Core MVC / API的Angular JS.

我有一个apiService来处理对服务器的所有POST和GET请求,如下所示:

module TBApp {

    export class apiService {

        static $inject = ['$http','notificationService'];

        constructor(private $http,private notificationService: notificationService) {

        }

        get(url,config,success,failure) {

            return this.$http.get(url,config)

                .then(result => { this.handleResponse(result,success); },result => { this.handleError(result,failure) });
        }

        post(url,data,failure) {

            return this.$http.post(url,data)
                .then(result => { this.handleResponse(result,failure) });
        }

        handleResponse(result,success) {

            alert('success');
            success(result);

        }

        handleError(result,failure) {

            if (result.status === '401') {

                this.notificationService.displayError('Authentication required.');
                //this.$rootScope.prevIoUsstate = this.$location.path();
                //this.$location.path('/login');

            }
            else if (failure !== null) {
                failure(result);
            }
        }
    }
}

现在,当我发送此请求时:

onCompanyChanged(selectedCompany,model,companyName) {

        this.apiService.post('/api/Dashboard/GetAssetListByCompany',{ companyId: selectedCompany.id },response => {

                this.assetListviewmodel = response.data.data;


            },response => {
            this.notificationService.displayError(response.data.message);
        });
    }

它没有绑定控制器中的companyId

这是控制器:

[Route("api/[controller]")]
    public class DashboardController : BaseController
    {
        [HttpPost]
        [Route("GetAssetListByCompany")]
        public IActionResult GetAssetListByCompany([FromBody]int companyId)
        {
            return CreateJsonResult(() =>
            {
                if (companyId == 0) { return new xPTJsonResult(null,xPTStatusCodesEnum.Success,"Company Id is 0"); }

               //var treeModel = _dashboardProvider.GetTreeModelByCompany(companyId,usermodel);

                return new xPTJsonResult(null,"Loaded assets successfully");

            });
        }

}

即使我在浏览器中检查了请求,也表明companyId在Payload中.

enter image description here

NOTE: The same function works when I post a viewmodel

编辑

在上面的场景中,我只将一个参数传递给控制器​​,但在某些情况下,我希望能够在不使用viewmodel的情况下传递2或3个参数.

例如

public IActionResult GetAssetListByCompany([FromBody]int companyId,[FromBody]int assetId)
{....

要么

public IActionResult GetAssetListByCompany([FromBody]int companyId,[FromBody]int assetId,[FromBody]bool canEdit = false)
    {.....

然后在客户端我可以这样做:

this.apiService.post('/api/Dashboard/GetAssetListByCompany',{ companyId: selectedCompany.id,assetId: 123 }.....

要么

this.apiService.post('/api/Dashboard/GetAssetListByCompany',canEdit: true,assetId: 22 }....

解决方法

这里最好的方法是遵循HTTP准则并将操作从POST更改为GET,因为您不修改任何数据.这很简单,仍然可以使用URI通过您的请求发送数据.

MVC改变了

有关各种选项,请参阅Model Binding,此处的最佳方法是基于查询字符串进行绑定,因为您只需要一个基本类型.如果您有一个基本类型数组仍然可以绑定到查询字符串,则查询字符串变量名称将为每个值重复一次.

因此,我们所做的唯一更改是指定参数来自查询字符串,并且它与Http Get请求而不是Post相关联.

[Route("api/[controller]")]
public class DashboardController : BaseController
{
    [HttpGet] // change to HttpGet
    [Route("GetAssetListByCompany")]
    public IActionResult GetAssetListByCompany([FromQuery]int companyId) // use FromQuery
    {
        return CreateJsonResult(() =>
        {
            if (companyId == 0) { return new xPTJsonResult(null,"Company Id is 0"); }

           //var treeModel = _dashboardProvider.GetTreeModelByCompany(companyId,usermodel);

            return new xPTJsonResult(null,"Loaded assets successfully");

        });
    }
}

AngularJS发生了变化

我们扩展apiService以允许使用HttpGet传递调用数据.这可以使用params on the $http call完成,它将使用名称作为查询字符串值名称和值作为值部分,根据传入的数据动态创建URL.

export class apiService {
    /* all other code is left as is,just change the get method to also accept data via the params. If null is passed in then it is ignored. */
    get(url,failure) {
        return this.$http({
            url: url,config: config,params: data,method: "GET"
            })
            .then(result => { this.handleResponse(result,failure) });
    }
}

在通话中我们只需要从post更改为get,它应该可以工作.

// only change from post to get
onCompanyChanged(selectedCompany,companyName) {
    this.apiService.get('/api/Dashboard/GetAssetListByCompany',response => {
            this.assetListviewmodel = response.data.data;
        },response => {
        this.notificationService.displayError(response.data.message);
    });
}

编辑 – 这很灵活

更重要的是,这种设计在角度方面是灵活的.如果您扩展MVC操作或具有采取其他参数的各种操作,则无需执行任何其他更改即可运行.例:

[HttpGet]
[Route("GetSomethingElseFromServer")]
public IActionResult GetSomethingElseFromServer([FromQuery]int companyId,[FromQuery]string assetName,[FromQuery]string companyModelNumber) // use FromQuery

对你的角度api的调用将是

this.apiService.get('/api/Dashboard/GetSomethingElseFromServer',{ companyId: companyId,assetName: somePassedInAssetNameVar,companyModelNumber: somePassedInModelNumber }

编辑 – 您也可以发送数组

要回答关于如何将多个基元类型作为数组发送的问题,您可以这样做.同样,这假设它不是您要发送的复杂类型,但是,例如,公司ID列表.

c#代码

[HttpGet]
[Route("GetAssetListByCompany")]
public IActionResult GetAssetListByCompany([FromQuery]int[] companyIds) // use an array of int ie. int[]. i changed the variable name to make it clear there can be more than 1

Angular调用,注意没有必要更改服务

onCompanyChanged(selectedCompany,{ "companyIds[]": [id1,id2,id3] },// note the name is Now enclosed in quotes,made plural,and includes []. The value is an array
        response => {
            this.assetListviewmodel = response.data.data;
        },response => {
        this.notificationService.displayError(response.data.message);
    });
}

编辑 – 如果你想要POST

您目前只发送一个原始字段,因此POST中的MVC框架无法正确反序列化.您需要将参数包装在视图模型中,将其作为查询字符串部分发送,或将其作为表单字段值发送.这是带有查询字符串部分的POST,它可以正常工作.

选项1

将其附加到URL

[HttpPost] // change to HttpGet
[Route("GetAssetListByCompany")]
public IActionResult GetAssetListByCompany([FromQuery] int companyId) // use FromQuery

角度呼叫

this.apiService.post('/api/Dashboard/GetAssetListByCompany/?companyId=' + selectedCompany.id +,null,// the rest of the code remains unchanged so I did not include it

选项2

扩展apiService以获取params对象,以便它可以构建您的查询.无论哪种方式,你都会遇到调用者不得不对http调用有所了解.

this.apiService.post('/api/Dashboard/GetAssetListByCompany',{companyId: selectedCompany.id},// the rest of the code remains unchanged so I did not include it

post(url,params,failure) {
    return this.$http({
        url: url,data: data,params: params,method: "POST"
        })
        .then(result => { this.handleResponse(result,failure) });
}

选项3

更新视图模型以采用复杂类型,这不需要更改角度代码.

public class ListByCompanyModel {
    public int CompanyId {get;set;}
}

[HttpPost] // change to HttpGet
[Route("GetAssetListByCompany")]
public IActionResult GetAssetListByCompany([FromBody] ListByCompanyModel model) // use FromQuery

ASP.NET MVC Web API2 AngularJS授权和身份验证

ASP.NET MVC Web API2 AngularJS授权和身份验证

我正在开发一个大型应用程序,其中包括后端的ASP.NET MVC和AngularJS Web Api2.以前我在我的应用程序中使用了MVC表单授权.有很多示例如何使用AngularJS Web Api使用基于令牌的授权,但找不到既适合这两种情况的完整解决方案.

请提供一些信息,我可以在这里阅读这个主题,也许分步示例,教程或博客,其中描述了两者的混合授权.

解决方法

>在您的WebAPI2应用程序 here is a good tutorial on implementing ASP.Identity 2中实现ASP.Net Identity 2.如果您将WebAPI和MVC5应用程序保留在不同的项目中,则会更好.
>决定您是否直接从AngularJS应用程序或从MVC应用程序连接到API
>如果直接从AngularJS应用程序调用API方法,请使用 this directive for OAuth2.将access_token存储在本地存储或cookie中.
>如果从您的MVC应用程序中调用API方法,请在客户端(使用本地存储或cookie)存储access_token,并将其用于对API的每次调用. here is a tutorial showing how to use AngularJS with ASP.Net MVC5
>确保您在生产中使用安全连接(https).

更新

您可以使用默认的ASP.Net提供程序为WebAPI.但默认的提供者最好使用EnityFramework.

我不是EF的粉丝,所以我自己使用了自定义提供商. Here is an overview的自定义识别提供商. This MySQL example帮助我很多实现自定义提供程序(但是我仍然使用sql Server,但是使用我们自己的内部DAL).

今天关于ASP.NET MVC和Angularjs一起+ ASP.NET Web APIasp.net mvc与asp.net的区别的分享就到这里,希望大家有所收获,若想了解更多关于AngularJS + ASP.NET Web API + ASP.NET MVC身份验证、AngularJs -.net MVC WebApi身份验证示例、angularjs – Angular JS MVC Web API模型/参数不绑定.NET Core、ASP.NET MVC Web API2 AngularJS授权和身份验证等相关知识,可以在本站进行查询。

本文标签: